<template>
  <div class="flex flex-row items-center flex-wrap gap-2">
    <NTag
      v-for="group in groups"
      :key="group.name"
      class="!cursor-pointer hover:bg-gray-200"
      @click="$emit('select-group', group)"
    >
      {{ group.title }}
    </NTag>
    <span v-if="groups.length === 0">-</span>
  </div>
</template>

<script lang="ts" setup>
import { NTag } from "naive-ui";
import { computed } from "vue";
import { useGroupStore } from "@/store";
import { getUserEmailFromIdentifier } from "@/store/modules/v1/common";
import { type User } from "@/types/proto/v1/auth_service";
import type { Group } from "@/types/proto/v1/group";

const props = defineProps<{
  user: User;
}>();

defineEmits<{
  (event: "select-group", group: Group): void;
}>();

const groupStore = useGroupStore();

const groups = computed(() => {
  const groups = [];
  for (const group of groupStore.groupList) {
    for (const member of group.members) {
      if (getUserEmailFromIdentifier(member.member) === props.user.email) {
        groups.push(group);
        break;
      }
    }
  }
  return groups;
});
</script>
